﻿using System.Collections.Generic;
using System.Data.Common;
using System.Data.SQLite;
using feather.core;
using feather.finder;
using feather.unit;

namespace CancerPanleReport.core
{
    class ActionControllerWrap : Singleton<ActionControllerWrap>
    {
        public ActionController actionController = new ActionController();

        public DbConnection DbConnection { get; set; }

        public object DoAction(string uri)
        {
            return DoAction(uri, null);
        }

        public object DoAction(string uri, IDictionary<string, object> args)
        {
            
            string action = uri;
            if (action == null) return null;

            int qidx = action.IndexOf("?");

            IDictionary<string, object> actionParams = args != null ? args : new Dictionary<string, object>();
            if (qidx != -1)
            {
                string newAction = action.Substring(0, qidx);
                string strParams = action.Substring(qidx + 1);
                foreach (string p in strParams.Split('&'))
                {
                    string[] kv = p.Split('=');
                    if (kv.Length == 2)
                    {
                        actionParams.Add(kv[0], kv[1]);
                    }
                }
                action = newAction;
            }

            return actionController.DoURI(action, actionParams);
        }

        public void Initialize(string path)
        {
            DbConnection = new SQLiteConnection(string.Format("Data Source={0}", path));
            DbConnection.Open(); 

            FormActionUnit formActionUnit = new FormActionUnit();
            actionController.AddObjectMethod(formActionUnit);

            actionController.AddObjectMethod(new CancerPanleReport.unit.FormActionUnit());

            SQLActionUnit sqlActionUnit = new SQLActionUnit();
            sqlActionUnit.DbConnection = DbConnection;
            actionController.AddObjectMethod(sqlActionUnit);

            HttpActionUnit httpActionUnit = new HttpActionUnit();
            actionController.AddObjectMethod(httpActionUnit);

            SQLActionFinder sqlActionFinder = new SQLActionFinder();
            sqlActionFinder.SQL = "select json from t_action where uri = '{0}'";
            sqlActionFinder.DbConnection = DbConnection;
            actionController.AddActionFinder(sqlActionFinder);

            
        }
    }
}
